from collections import OrderedDict
from django import http
import requests
import json
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.views import APIView
from rest_framework.response import Response

from book.models import Book
from equipments.models import Equipment
from equipments.serializers import EquipmentModelSerializer
from rest_framework import status
from common import CommonResult
from utils.MyPageNumberPagination import MyPageNumberPagination, QueryWrapper
from django.db import transaction

# 序列化器和APIview实现列表视图(获取所有设备、增加单个设备)
from utils.getConfigurations import generateConfiguration


class EquipmentAPiView(APIView):
    # 查询所有设备
    def get(self, request):
        # 1,查询所有的设备
        equipments = Equipment.objects.all()
        # 创建分页对象
        page = MyPageNumberPagination()
        # 在数据库获取分页数据
        page_roles = page.paginate_queryset(queryset=equipments, request=request, view=self)
        # 2,将对象列表转成字典列表
        serializer = EquipmentModelSerializer(instance=page_roles, many=True)
        # 3,返回响应, safe=False允许非字典数据可以被返回
        return page.get_paginated_response(serializer.data)

    # 提交设备
    def post(self, request):
        # 1,获取参数
        data_dict = request.data.copy()
        data_dict['e_id'] = data_dict['e_tag']
        idrac_ip = data_dict['e_iDrac_ip']
        data_dict['e_configuration'] = generateConfiguration(idrac_ip)
        # 创建序列化器
        serializer = EquipmentModelSerializer(data=data_dict)
        # 校验 入库
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 4,返回响应
        return CommonResult.ok("添加成功", serializer.data)


# 2, 获取单个设备,修改单个设备信息,删除设备信息(详情视图)
class EquipmentDetailView(APIView):
    # 获取单个设备
    def get(self, request, eid):
        # 1,获取书籍
        equipment = Equipment.objects.filter(e_id=eid)
        if equipment.exists():
            serializer = EquipmentModelSerializer(instance=equipment, many=True)
            idrac_ip = serializer.data[0]['e_iDrac_ip']
            result = serializer.data[0]
            result['e_configuration'] = generateConfiguration(idrac_ip)

            return CommonResult.ok("查询成功",result)

        else:
            return CommonResult.params_error("查询失败，该设备不存在")

    # 修改单个设备信息
    def put(self, request, eid):
        # 1,获取数据,获取对象
        data_dict = request.data
        equipment = Equipment.objects.get(e_id=eid)
        if equipment.e_status == 0:
            # 创建序列化器
            serializer = EquipmentModelSerializer(instance=equipment, data=data_dict)
            # 3校验、入库
            serializer.is_valid(raise_exception=True)
            serializer.save()
            # 4,返回响应
            return CommonResult.ok("修改成功", serializer.data)
        if equipment.e_status == 1:
            return CommonResult.params_error("该设备正在使用中，不可修改")
        if equipment.e_status == 2:
            return CommonResult.params_error("该设备已损坏，不可修改")

        return Response(data_dict)

    # 删除设备信息
    def delete(self, request, eid):
        # 1,删除设备
        equipment = Equipment.objects.get(e_id=eid)
        book = Book.objects.filter(e_id=eid)
        if equipment.e_status == 1:
            return CommonResult.params_error("该设备正在被使用，不可删除")
        if equipment.e_status == 0:
            # 删除设备
            equipment.delete()
            # 删除该设备关联的订单信息
            book.delete()
            return CommonResult.ok("删除成功")
        # 如果设备是不可用状态 那么直接删除
        if equipment.e_status == 2:
            equipment.delete()
            return CommonResult.ok("删除成功")


"""""""""""""""视图集"""""""""""""""""
from rest_framework.viewsets import ModelViewSet
from equipments.models import Equipment
from equipments.serializers import EquipmentModelSerializer


class EquipmentModelViewSets(ModelViewSet):
    queryset = Equipment.objects.all()
    serializer_class = EquipmentModelSerializer
    pagination_class = MyPageNumberPagination

    # 获取空闲的设备
    def status_0(self, request):
        # 获取指定设备
        equipments = Equipment.objects.filter(e_status=0)
        if equipments.exists():
            # 创建分页对象
            page = MyPageNumberPagination()
            # 在数据库获取分页数据
            page_roles = page.paginate_queryset(queryset=equipments, request=request, view=self)
            # 创建序列化对象
            serializer = self.get_serializer(instance=page_roles, many=True)
            # 返回响应
            return page.get_paginated_response(serializer.data)
        else:
            return CommonResult.params_error("无空闲设备")

    # 获取使用中的设备
    def status_1(self, request):
        # 获取指定设备
        equipments = Equipment.objects.filter(e_status=1)
        if equipments.exists():
            page = MyPageNumberPagination()
            # 在数据库获取分页数据
            page_roles = page.paginate_queryset(queryset=equipments, request=request, view=self)
            # 创建序列化对象
            serializer = self.get_serializer(instance=page_roles, many=True)
            # 返回响应
            return page.get_paginated_response(serializer.data)
        else:
            return CommonResult.params_error("无正在使用的设备")

    # 获取不可使用的设备
    def status_2(self, request):
        # 获取指定设备
        equipments = Equipment.objects.filter(e_status=2)
        if equipments.exists():
            page = MyPageNumberPagination()
            # 在数据库获取分页数据
            page_roles = page.paginate_queryset(queryset=equipments, request=request, view=self)
            # 创建序列化对象
            serializer = self.get_serializer(instance=page_roles, many=True)
            # 返回响应
            return page.get_paginated_response(serializer.data)
        else:
            return CommonResult.params_error("所有设备完好")


from utils.MyPageNumberPagination import QueryWrapper


# 获取所有设备，并且包含使用中设备的订单信息
class NewEquipmentDetailView(APIView):
    @transaction.atomic()
    def get(self, request):
        sql = 'SELECT a.u_id,a.subscribe_date,a.expire_date,b.* FROM  hwb_book  a RIGHT JOIN hwb_equipment b ON a.e_id=b.e_id AND a.b_status=true '
        queryset = QueryWrapper(sql)
        page = MyPageNumberPagination()
        page_roles = page.paginate_queryset(queryset=queryset, request=request)
        return page.get_paginated_response(page_roles)

# 获取某个cluster下的所有设备，并且包含使用中设备的订单信息
class EquipmentClusterDetailView(APIView):
    @transaction.atomic()
    def get(self, request):
        sql = 'SELECT a.u_id,a.subscribe_date,a.expire_date,b.* FROM  hwb_book  a RIGHT JOIN hwb_equipment b ON a.e_id=b.e_id AND a.b_status=true  where e_cluster=%s' % (
            request.query_params.get('e_cluster'))
        queryset = QueryWrapper(sql)
        page = MyPageNumberPagination()
        page_roles = page.paginate_queryset(queryset=queryset, request=request)
        print(page_roles)
        return page.get_paginated_response(page_roles)

# 获取不同状态设备的数量
class EquipmentStatusView(APIView):
    def get(self, request):
        count = Equipment.objects.all().count()
        status0 = Equipment.objects.filter(e_status=0).count()
        status1 = Equipment.objects.filter(e_status=1).count()
        return Response({'ALL_Equipment_usage': count, 'Available_Equipments': status0, 'Occupied_Equipments': status1})

# 获取所有cluster下的所有设备，并且包含使用中设备的订单信息
class EquipmentClusterView(APIView):
    @transaction.atomic()
    def get(self, request):
        sql1 = 'select distinct e_cluster from hwb_equipment'
        queryset1 = QueryWrapper(sql1)
        page1 = MyPageNumberPagination()
        page_roles1 = page1.paginate_queryset(queryset=queryset1, request=request)
        allResult = []

        for dic in page_roles1:
            sql = "SELECT a.u_id,a.subscribe_date,a.expire_date,b.* FROM  hwb_book  a RIGHT JOIN hwb_equipment b ON a.e_id=b.e_id AND a.b_status=true  where e_cluster='%s'" % (
                dic['e_cluster'])
            queryset = QueryWrapper(sql)
            page = MyPageNumberPagination()
            page_roles = page.paginate_queryset(queryset=queryset, request=request)
            sql_free = "SELECT a.u_id,a.subscribe_date,a.expire_date,b.* FROM  hwb_book  a RIGHT JOIN hwb_equipment b ON a.e_id=b.e_id AND a.b_status=true  where b.e_status=0 and e_cluster='%s'" % (
                dic['e_cluster'])
            queryset = QueryWrapper(sql_free)
            page_free = MyPageNumberPagination()
            page_roles_free = page_free.paginate_queryset(queryset=queryset, request=request)
            result = {}
            result['e_cluster'] = dic['e_cluster']
            result['total'] = len(page_roles)
            result['free'] = len(page_roles_free)
            result['node_list'] = page_roles
            allResult.append(result)
        return CommonResult.ok('查询成功', allResult)
        # return page.get_paginated_response(page_roles)


class UpdateEuipmentDetailView(APIView):
    def get(self, request):
        # equipment = Equipment.objects.get(e_id=eid)
        # idrac_ip = equipment.e_iDrac_ip
        idrac_ip = '20.12.95.32'
        systemID_url = "https://" + idrac_ip + "/redfish/v1/Systems/System.Embedded.1"
        members_url = "https://" + idrac_ip + "/redfish/v1/UpdateService/FirmwareInventory"
        # 模拟浏览器头部信息，向服务器发送消息，此处使用的是Linux火狐浏览器头部信息
        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'
        }
        # 登陆网页所需的用户名和密码
        auths = ('root', 'calvin')
        response_system_id = requests.get(systemID_url, auth=auths, headers=header, verify=False)
        response_members = requests.get(members_url, auth=auths, headers=header, verify=False)
        # 对response进行编码，以防出现乱码
        response_members.encoding = 'UTF-8'
        response_system_id.encoding = 'UTF-8'
        response_members_data = json.loads(response_members.text)
        response_system_id_data = json.loads(response_system_id.text)

        result = {}
        result['SystemID'] = response_system_id_data['Oem']['Dell']['DellSystem']['SystemID']
        result['Members'] = response_members_data['Members']
        print(result)
        return Response(result)
